package com.bbm.communitysystem.filter;

import com.bbm.communitysystem.core.Token;
import com.bbm.communitysystem.core.filter.Verify;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
//@Component
@RequiredArgsConstructor
public class TokenFilter implements Filter , Ordered {

    private final Token token;

    private final Verify verify;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        if (verify.verifyAdmin(request)) {
            filterChain.doFilter(servletRequest, response);
            return;
        }

        if (verify.verifyError(request)) {
            response.sendError(5000, verify.getError(request));
            filterChain.doFilter(servletRequest, response);
            return;
        }


        String auth = request.getHeader("auth");
        if (auth == null || auth.isEmpty()) {
            log.info("auth is null");

            response.sendError(5000, "无授权信息");
            response.setStatus(5000);

            verify.addError(request, "无授权信息");

            filterChain.doFilter(servletRequest, response);
            return;
        }

        int verifyToken = token.verify(auth);

        if (verifyToken == 0) {

            response.sendError(5000, "授权过期");

            verify.addError(request, "授权过期");

            filterChain.doFilter(servletRequest, response);
            return;
        }

        if (verifyToken == 2) {

            auth = token.flushToken(auth);

            response.addHeader("token", auth);

            response.addHeader("Access-Control-Expose-Headers", "token");
        }



        filterChain.doFilter(servletRequest, response);
    }

    @Override
    public int getOrder() {
        return 100;
    }
}
